<?php

class Product
{
    public static $pagesize = 10;

    /**
     * 商品分类
     * @param $args
     * @return mixed
     */
    public static function getProductCategoryList($args)
    {
        global $db;
        global $redis;
        global $utility;

        $db_prefix = \Config\Json::$config['db_prefix'];
        $redis_prefix = \Config\Json::$config['redis_prefix'];

        $redis_key = $redis_prefix.'Product_Category_All';

        $data = $utility->redisGet($redis_key);

        if(!$data){
            $subCategory = array();
            # 主分类
            $pclass_sql = "select `id`,`title` from `{$db_prefix}product_category` where state=1 and parentid=0 order by sort ASC";
            $parentCategory = $db->query($pclass_sql);

            //取出所有对应的子分类
            foreach($parentCategory as $var) {
                $pclass_sql = "select `id`,`title`,REPLACE(`icon`,'/upload/','') as icon,hot,parentid from `{$db_prefix}product_category` where state=1 and parentid=".$var['id']." order by sort desc";
                $subCategory[$var['id']] = $db->query($pclass_sql);
            }
            //取出分类顶部广告
            $banner_sql = "select url,REPLACE(`pic`,'/upload/','') as pic from `{$db_prefix}advs` where state=1 and categoryid=2 order by sort desc";
            $banner_data = $db->query($banner_sql,2);

            $data['category'] = $parentCategory;
            $data['subcategory'] = $subCategory;
            $data['banner_data'] = $banner_data;
            $utility->redisSet($redis_key, $data);
        }
        return $data;
    }

    /**
     * 拉取兑换商品首页的BANNER数据
     * @param $args
     * @return \Swoole\Database\MySQLiRecord
     */
    public static function getProductBanner($args)
    {
        global $db;
        global $redis;
        global $utility;

        $db_prefix = \Config\Json::$config['db_prefix'];
        $redis_prefix = \Config\Json::$config['redis_prefix'];

        $redis_key = $redis_prefix.'Product_Banner';

        $data = $utility->redisGet($redis_key);

        if(!$data){
            //取出分类顶部广告
            $banner_sql = "select url,REPLACE(`pic`,'/upload/','') as pic from `{$db_prefix}advs` where state=1 and categoryid=3 order by sort desc";
            $banner_data = $db->query($banner_sql,3);
            $data = $banner_data;
            //如果有数据即缓存
            if($data) {
                $utility->redisSet($redis_key, $data);
            }
        }
        return $data;
    }
    /**
     * 兑换首页商品列表
     * @param $args
     */
    public static function getDefaultProductList($args)
    {
        global $db;
        global $redis;
        global $utility;

        $db_prefix = \Config\Json::$config['db_prefix'];
        $redis_prefix = \Config\Json::$config['redis_prefix'];

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array("ps","pc",'keys', 'cid', 'sid', 'keys', 'sort');
        $get_args = $utility->get_url_args($args, $url_args);
        $page_args = $utility->get_page_args($args, $url_args);

        if(empty($get_args['ps'])) $get_args['ps'] = self::$pagesize;
        if(empty($get_args['pc'])) $get_args['pc'] = 1;

        # 生成Redis键
        $redis_key = json_encode($get_args);
        $redis_key = $redis_prefix.'products_'.md5($redis_key);

        $data = $utility->redisGet($redis_key);

        if(!$data){
            $where_txt = " `state`=1";


            # 组装时间查询条件
            # $begintimes = strtotime(date('Y-m-d'));
            # $endtimes = $begintimes + 86400;
            #

            # 组装查询条件
            if(!empty($get_args['cid'])) $where_txt .= " AND `categoryid`=".$get_args['cid'];
            if(!empty($get_args['sid'])) $where_txt .= " AND `categorysubid`=".$get_args['sid'];
            if(!empty($get_args['keys'])) $where_txt .= " AND (`title` LIKE '%".$get_args['keys']."%' OR FIND_IN_SET('".$get_args['keys']."',`keys`))";

            # 组装查询
            $tablename = $db_prefix . 'products';
            $fields = "`code`,`title`,REPLACE(`icon1`,'/upload/','') as icon,`price`,`pricenet`,`reminder`,`pricescore`";

            $sql = "SELECT ~field~ FROM `{$tablename}` WHERE {$where_txt} ~order~ ~limit~";
            # 组装排序
            $orderby_field = (empty($get_args['sort']) ? 'sort' : $get_args['sort']);
            $orderby = " ORDER BY `{$orderby_field}` DESC";

            //取出当前页的数据
            $sql_arr = array(
                'field' => $fields,
                'page_current' => $get_args['pc'],
                'pagesize' => $get_args['ps'],
                'order' => $orderby,
            );
            $data = $utility->getTableRows($sql, $sql_arr);
            $utility->redisSet($redis_key, $data);
        }
        return $data;
    }

    public static function getProductForCode($args)
    {
        global $db;
        global $redis;
        global $utility;

        $db_prefix = \Config\Json::$config['db_prefix'];
        $redis_prefix = \Config\Json::$config['redis_prefix'];

        $data = array();

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array("id");
        $get_args = $utility->get_url_args($args, $url_args);

        if(empty($get_args['id'])){
            return $data;
        }

        # 生成Redis键
        $redis_key = $redis_prefix.'products_item_'.$get_args['id'];

        $data = $utility->redisGet($redis_key);

        if(!$data){
            $where_txt = " `code`='{$get_args['id']}' AND `state`=1";
            # 组装查询
            $tablename = $db_prefix . 'products';
            $sql = "SELECT * FROM `{$tablename}` WHERE {$where_txt} LIMIT 1";
            $data = $db->row($sql);
            if($data) {
                unset($data['id']);
                unset($data['state']);
                unset($data['website']);
                //unset($data['title']);
                unset($data['keys']);
                foreach ($data as $key=>$v)
                {
                    $data[$key] = str_replace('/upload/','',$v);
                }
                $sql = "SELECT `content` FROM `{$db_prefix}products_con` WHERE `code`='{$get_args['id']}' LIMIT 1";
                $content = $db->row($sql);
                if ($content) {
                    $data['content'] = $content['content'];
                }
                $utility->redisSet($redis_key, $data);
            }

        }
        return $data;
    }

    # region 商品兑换支付
    public static function exchangeOrderPay($paras)
    {
        global $db;
        global $utility;

        $mastArgs = array(
            'cmd',
            'token',
            'amount|F',
            'proid',
            'numbers|N',
            'payfrom',
            'consignee',
            'address',
            'tel',
            'remarks',
            'pricescore',
            'paytype',
            'amountscore|F',
        );
        $paras = $utility->get_url_args($paras, $mastArgs);
        $result = array('state'=>404, 'cmd'=>$paras['cmd'], 'msgid'=>404);
        if(empty($paras['paytype']))
        {
            $result['msgid'] = 10045;
            return $result;
        }
        if(empty($paras['numbers']) || empty($paras['proid'])){
            return $result;
        }
        if($paras['numbers']<=0){
            return $result;
        }

        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);


        if($user['state']==200) {
            if($user['usertype'] ==0){
                return array(
                    'cmd' => $paras['cmd'],
                    'state' => 404,
                    'msgid' => 10085,
                );
            }

            $usercoin = $user['usercoin'] - $user['reggivecoin'];
            $userscore = $user['userscore'];

            # 找出兑换商品的数据进行重新计算
            $sql = "SELECT * FROM `".\Config\Sys::$dbprefix."products` WHERE `code`='".$paras['proid']."'  AND `state`=1 LIMIT 1";
            $pro = $db->row($sql);
            if(!$pro){
                return array(
                    'cmd' => $paras['cmd'],
                    'state' => 404,
                    'msgid' => 10085,
                    'msg' => '商品不存在或已下架'
                );
            }
            $amount = 0;
            if($paras['paytype']=='usercoin') {
                $amount = round($paras['numbers'] * $pro['price'], 2);
                if ($amount > $user['usercoin']) {
                    return array(
                        'cmd' => $paras['cmd'],
                        'state' => 404,
                        'msgid' => 10005,
                    );
                }
            }
            $scoreamount = 0;
            if($paras['paytype']=='userscore') {
                # 如果积分功能没有开启将返回错误提示 - enablescore
                $enablescore = intval($utility->getSystemParams('enablescore'));
                if(!$enablescore){
                    return array(
                        'cmd' => $paras['cmd'],
                        'state' => 404,
                        'msgid' => 10111, // 功能已关闭
                    );
                }
                $scoreamount = round($paras['numbers'] * $pro['pricescore'], 2);
                if ($scoreamount > $user['userscore']) {
                    return array(
                        'cmd' => $paras['cmd'],
                        'state' => 404,
                        'msgid' => 10074,
                    );
                }
            }
            # region 数据事务处理
            $db->beginTrans();
            $insert_log = array(
                'uid' => $user['uid'],
                'orderid' => $utility->neworderno(),
                'proid'=>$paras['proid'],
                'price'=>$pro['price'],
                'numbers'=>$paras['numbers'],
                'amount'=>$amount,
                'scoreamount' => $scoreamount,
                'paytype' => $paras['paytype'],
                'consignee'=>$paras['consignee'],
                'address'=>$paras['address'],
                'tel'=>$paras['tel'],
                'remarks'=>$paras['remarks'],
                'actiontime'=>time(),
            );
            $insert_id = $db->insert(\Config\Sys::$dbprefix.'exchange_orders')->cols($insert_log)->query();
            if($paras['paytype']=='usercoin') {
                # 扣余额
                $utility->setCoin(
                    array(
                        'uid' => $user['uid'],
                        'coin' => (0 - floatval($amount)),
                        'gameid' => 0,
                        'liqtype' => 22, // 商品兑换
                        'ex1' => $insert_id,
                        'ex2' => $insert_log['orderid'],
                    )
                );
                $usercoin = $usercoin - $amount;
            }
            if($paras['paytype']=='userscore') {
                $utility->setScore(
                    array(
                        'uid' => $user['uid'],
                        'score' => (0 - floatval($scoreamount)),
                        'gameid' => 0,
                        'liqtype' => 3, // 商品兑换
                        'ex1' => $insert_id,
                        'ex2' => $insert_log['orderid'],
                    )
                );
                $userscore = $userscore - $scoreamount;
            }
            $db->commitTrans();
            # 组织返回数据
            $result = array(
                'state' => 200,
                'cmd' => $paras['cmd'],
                'title' => $pro['title'],
                'amount' => $amount,
                'amountscore' => $scoreamount,
                'paytype' => $paras['paytype'],
                'orderid' => $insert_log['orderid'],
                'actiontime' => date('Y-m-d H:i:s', $insert_log['actiontime']),
                'usercoin' => $usercoin,
                'userscore' => $userscore,
            );
            # endregion
        }else{
            $result = array(
                'state' => $user['state'],
                'cmd' => $paras['cmd'],
                'msgid' => $user['msgid'],
            );
        }
        return $result;
    }
    # endregion
}